package jxtcp

import (
	"fmt"
	"log"
	"net"
	"sync"

	"gitee.com/frankwangli/jxmap"
	"github.com/google/uuid"
)

type Server struct {
	listener    net.Listener //侦听对象
	onMessage   func(m *Message)
	clientmap   *jxmap.JxMap[string, *ServerConn]
	messageList chan *Message
}

var newlinkLocker sync.Mutex

// 新的一个Tcp服务端
func NewServer(address string, f func(m *Message)) (*Server, error) {
	l, err := net.Listen("tcp", address)
	if err != nil {
		return nil, err
	}
	outData := &Server{
		listener:    l,
		onMessage:   f,
		clientmap:   jxmap.New[string, *ServerConn](),
		messageList: make(chan *Message, 100),
	}
	outData.init()
	return outData, nil
}
func (s *Server) init() {
	go func() {
		for {
			conn, err := s.listener.Accept()
			if err != nil {
				log.Printf("新建连接失败: %v", err)
				continue
			}
			go s.handleConnection(conn)
		}
	}()
}
func (s *Server) GetCount() int {
	return s.clientmap.Size()
}
func (s *Server) SendMessage(m *Message) error {
	var sendError error
	sended := false
	for {
		s.clientmap.Range(func(id string, conn *ServerConn) bool {
			if conn.MachineId == m.MachineId {
				ok, err := conn.SendMessage(m)
				if ok {
					sendError = err
					sended = true
					return false
				}
			}
			return true
		})
		if sended {
			break
		}
	}
	return sendError
}
func (s *Server) handleConnection(conn net.Conn) {
	fmt.Println("创建新的服务端链接")
	c := NewServerConn(uuid.NewString(), conn, s.onMessage, func(id string) {
		s.clientmap.Delete(id)
	})
	s.clientmap.Set(c.id, c)
}
